<template>
	<div class="thePage">
		<!-- 没有登录 -->
		<div v-if="!isLogin">
			<van-cell class="member" is-link to="login">
				<template #icon>
					<van-image width="100" height="100" :src="avatar_default" />
				</template>
				<template #title>
					<span class="title">登录 / 注册</span>
				</template>
			</van-cell>

		</div>
		<!-- 已经登录 -->
		<div v-else>
			<van-cell class="member">
				<template #icon>
					<van-image width="100" height="100" :src="avatar_my" />
				</template>
				<template #title>
					<span class="title">{{name}}</span>
				</template>
			</van-cell>

			<!-- 用户课操作功能列表 -->
			<van-cell v-for="(item, i) of cellItems" :key="i" :icon="item.img" :title="item.title" is-link
				:to="{name:item.name}" />
			<van-cell @click="onLoginOut" icon="user-o" title="退出登录" is-link />
		</div>
	</div>
</template>

<script>
	// Vue3 + vite 加载图片资源
	import avatar_default from "@/assets/images/avatar_default.png"

	// 导入数据本地存储的方法
	import { getTokenLocal, removeTokenLocal, getUserLocal } from "@/utils/auth.js"

	// 导入用到的接口
	import { getDetailByIdAPI, logoutAPI } from "@/api/user.js"

	export default {
		name: "user",
		data() {
			return {
				isLogin: false, //默认没有登录
				avatar_default: avatar_default, //没有登录时显示的头像				
				name: "", //登录用户名
				avatar_my: "", //登录用户头像
				cellItems: [{
						title: "我的订单",
						name: "orderList",
						img: "orders-o",
					},
					{
						title: "收货地址",
						name: "addressList",
						img: "envelop-o",
					},
					{
						title: "我的收藏",
						name: "working",
						img: "point-gift-o",
					},
					{
						title: "个人资料",
						name: "profile",
						img: "user-o",
					},
					{
						title: "修改密码",
						name: "updatePwd",
						img: "records",
					},
				],
			}
		},
		mounted() {
			// 当前会话存储中有没有token  MYTOKEN
			this.isLogin = getTokenLocal() ? true : false
			if (this.isLogin) {
				// 获取用户名
				let user = getUserLocal()
				this.name = user.name
				// 获取用户头像
				getDetailByIdAPI(user.id).then(result => {
					//console.log(result)
					this.avatar_my = this.APIDomainName + result.data.avatar
				})
			}
		},
		methods: {
			onLoginOut() {
				logoutAPI().then(result => {
					// 将保存在的 token 清空
					removeTokenLocal()
					this.isLogin = false
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.thePage {
		padding: 40px 10px 10px 10px;
		background-color: white;
	}

	.member {
		margin-top: 15px;
		padding: 10px;
		background: linear-gradient(90deg, #28a2ff, #ffd787);
		box-shadow: 0 0.1rem 0.25rem #f8e3c6;
		align-items: center;
	}

	.title {
		padding-left: 20px;
		font-size: 24px;
		color: #4110f1;
	}
</style>